package com.turing.post.organization.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.organization.util.VoucherOrderActionDetail;
import com.turing.post.organization.util.VoucherOrderActionDetailDao;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

/**
 * @author wzd
 * @2013-03-12
 */
@Stateless(mappedName = "organization.impl.VoucherOrderActionDetailDaoImpl")
@Remote
@Local
public class VoucherOrderActionDetailDaoImpl implements VoucherOrderActionDetailDao {

	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	/**
	 * 根据条件查询迁移列表
	 * 
	 * @param id
	 *            调入机构号
	 * @return 凭证调拨单状态表列表
	 */
	@SuppressWarnings("unchecked")
	public List<VoucherOrderActionDetail> getVoucherOrderActionDetailList(BigInteger transferOrderId){
		if (transferOrderId == null)
			return null;
		String sql = "select t.* from VoucherOrderActionDetail t where t.transferorderid=?1 order by actionTime";
//		System.out.println(transferOrderId);
		Query query = _em.createNativeQuery(sql, VoucherOrderActionDetail.class);
		query.setParameter(1, transferOrderId);
		return query.getResultList();
	}

	/**
	 * 新增迁移
	 * 
	 * @param VoucherOrderActionDetail
	 *            迁移
	 * @throws PCPSApplicationException
	 */
	@Override
	public void insertVoucherOrderActionDetail(
			VoucherOrderActionDetail voucherOrderActionDetail)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, voucherOrderActionDetail);
	}
	/**
	 * 根据明细id，时间，操作人检索本调拨单是否，一个人操作了多个操作（如：一个人先创建，再操作后面的任何一个步骤）
	 */
	public int IsTransferOrderActionDetail(BigInteger TRANSFERORDERID,BigInteger OPERID){
		String sql = "select nvl(count(*),0) from VoucherOrderActionDetail where 1=1"
		           + " and TRANSFERORDERID=?1 and OPERID=?2";
		Query query=_em.createNativeQuery(sql);
		query.setParameter(1, TRANSFERORDERID);
		query.setParameter(2, OPERID);
		return Integer.parseInt(query.getSingleResult().toString());
	}
	/**
	 * 根据id,起止状态，交易类型检索一条记录
	 */
	public VoucherOrderActionDetail getVoucherOrderActionDetailBycon(BigInteger transferOrderId,String sartstuts,String endstuts,String trantype){
		String sql = "select * from VoucherOrderActionDetail where "
	           + "  TRANSFERORDERID=?1 and initialstatus=?2 and endstatus=?3 and actiontype=?4";
	    Query query=_em.createNativeQuery(sql,VoucherOrderActionDetail.class);
	    query.setParameter(1, transferOrderId);
	    query.setParameter(2, sartstuts);
	    query.setParameter(3, endstuts);
	    query.setParameter(4, trantype);
	    return ((VoucherOrderActionDetail) query.getSingleResult());
	}
}
